<template>
  <div>

    <el-main>

      <!-- 面包屑 -->
      <div class="bg-breadcrumb" style="margin-bottom: 15px;">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/teacher/teacherhomepage' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>修改个人信息</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <!-- 编辑个人信息 -->
      <el-card shadow="always" :body-style="{ padding: '20px' }">
        <el-form :model="currentNews" ref="editNewsForm" :rules="addNewsRules" label-width="80px" :inline="false" size="small">
          <el-form-item label="新闻标题" prop="title">
            <el-input v-model="currentNews.title"></el-input>
          </el-form-item>
          <el-form-item label="编辑人" prop="editor">
            <el-input v-model="currentNews.editor"></el-input>
          </el-form-item>
          <el-form-item label="来源" prop="source">
            <el-input v-model="currentNews.source"></el-input>
          </el-form-item>
          <el-form-item label="新闻内容" prop="content">
            <el-input type="textarea" v-model="currentNews.content"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="editNewsSubmit()">提交</el-button>
            <el-button @click="editNewsDialog = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-card>

    </el-main>


  </div>
</template>

<script>
import { toDateString } from '@/utils/time.js'
export default {
  data () {
    return {
      addNewsRules: {
        title: [
          { required: true, message: '请输入新闻标题', trigger: 'blur' }
        ],
        editor: [
          { required: true, message: '请输入编辑人', trigger: 'blur' }
        ],
        source: [
          { required: true, message: '请输入新闻来源', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入新闻内容', trigger: 'blur' }
        ]
      },

      currentPage: 1,
      goodStudentList: [],
      goodTeacherList: [],
      newsNum: 0,
      addNewsForm: {
        title: "",
        editor: "",
        source: "",
        content: ""
      },
      addNewsDialog: false,
      editNewsDialog: false,
      newsList: [],
      currentNews: {},
      previewImg: '',
      addPic: '',
      changeImg: ''
    }
  },
  created () {
    this.getNewsList()
  },
  methods: {
    async getNewsList () {
      const { data: res } = await this.$http.post(`board/all/getNewsList?page=${this.currentPage - 1}&rows=10`)
      console.log(res)
      if (!res.state) return this.$message.error(res.msg);
      this.newsList = this.foreachObj(res.detail.list)
      this.newsNum = res.detail.total
    },

    // 新增课程上传图片函数
    addUploadImg (e) {
      const file = e.target.files[0]
      if (file.length == 0) {
        this.previewImg = ''
        return
      }
      // 使用 FileReader 读取文件对象
      const reader = new FileReader()
      // 读取完毕后获取结果，写入到previewImg中
      reader.onload = event => {
        this.previewImg = event.target.result
      }
      // 把文件对象作为一个 dataURL 读入
      reader.readAsDataURL(file)
      // 创建FormData
      const param = new FormData() // 创建form对象
      param.append('file', file, file.name) // 通过append向form对象添加数据
      console.log(param.get('file')) // FormData私有类对象，访问不到，可以通过get判断值是否传进去
      this.addPic = param
    },

    // 修改课程上传图片函数
    changeImgUpload (e) {
      const file = e.target.files[0]
      if (file.length == 0) {
        this.changeImg = ''
        return
      }
      // 使用 FileReader 读取文件对象
      const reader = new FileReader()
      // 读取完毕后获取结果，写入到changeImg中
      reader.onload = event => {
        this.changeImg = event.target.result
      }
      this.currentNews.avatarUrl = ''
      // 把文件对象作为一个 dataURL 读入
      reader.readAsDataURL(file)
      const param = new FormData() // 创建form对象
      param.append('file', file, file.name) // 通过append向form对象添加数据
      console.log(param.get('file')) // FormData私有类对象，访问不到，可以通过get判断值是否传进去
      this.changePic = param
    },

    // 新增一个新闻
    addNews () {
      this.addNewsDialog = true;
      this.addNewsForm = {
        title: "",
        editor: "",
        source: "",
        content: ""
      }
    },

    // 新增一条新闻提交按钮
    addNewsSubmit () {
      this.$refs.addNewsForm.validate(valid => {
        if (!valid) return
        let url = `board/admin/createNews`
        this.$http({
          url: url,
          method: 'post',
          data: this.addNewsForm
        }).then(async result => {
          const res = result.data
          console.log(res)
          if (!res.state) return this.$message.error(res.msg)
          if (this.addPic) {
            console.log(this.addPic.get('file'))
            const config = {
              headers: {
                'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
              }
            }
            const { data: respon } = await this.$http.post('board/admin/newsAvatar?id=' + res.detail.id, this.addPic, config)
            console.log(respon)
            if (!respon.state) return this.$message.error('上传图像出错!')
          }
          this.addNewsDialog = false
          this.$message.success(res.msg)
          this.getNewsList()
          this.previewImg = ''
        })
      })
    },

    // 编辑一个新闻
    editNews (news) {
      this.editNewsDialog = true
      this.currentNews = news
    },

    // 编辑新闻提交按钮
    editNewsSubmit () {
      this.$refs.editNewsForm.validate(valid => {
        if (!valid) return
        let url = `board/admin/updateNews`
        let data = {}
        data.title = this.currentNews.title
        data.editor = this.currentNews.editor
        data.source = this.currentNews.source
        data.content = this.currentNews.content
        data.id = this.currentNews.id
        this.$http({
          url: url,
          method: 'post',
          data: data
        }).then(async result => {
          const res = result.data
          if (!res.state) return this.$message.error(res.msg)
          if (this.changePic) {
            // 接入另一个传入课程图片的接口
            console.log(this.changePic.get('file'))
            const config = {
              headers: {
                'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
              }
            }
            const { data: respon } = await this.$http.post('board/admin/newsAvatar?id=' + res.detail.id, this.changePic, config)
            console.log(respon)
            if (!respon.state) return this.$message.error("修改图片出错！")
            // 最后还需要将changeImg置空
            this.changeImg = ''
          }
          this.$message.success(res.msg)
          this.editNewsDialog = false
          this.getNewsList()
        })
      })
    },

    // 删除一条新闻
    deleteNews (id) {
      this.$confirm('此操作将永久删除此新闻, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const { data: res } = await this.$http.post(`board/admin/deleteNews?id=${id}`)
          if (!res.state) return this.$message.error(res.msg)
          console.log(res)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getNewsList()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },

    // 更改页码，进行导航
    async handleCurrentChange (val) {
      // console.log(val)
      this.currentPage = val
      this.getNewsList()
    },

    // 前端处理后端数据
    foreachObj (data) {
      data.map(item => {
        item.createTime = toDateString(item.createTime)
        item.updateTime = toDateString(item.updateTime)
      })

      return data
    },

    handleClose(done) {
      this.changeImg = ''
      this.previewImg = ''
      done()
    }
  }
}
</script>

<style lang="less" scoped>

</style>
